<?php

namespace App\Http\Logic;

use App\Models\OsanGroup;
use App\Models\OsanGroupMenu;
use App\Models\OsanGroupUser;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Support\Facades\Log;

class Login extends Logic
{
    /**
     * jwt 加密
     * @return string
     */
    public function createToken(int $uid = 0): string
    {
        if (!$uid) {
            return '';
        }
        $conf = config('jwt');
        $signTime = time();
        $token = JWT::encode([
            'uid' => $uid,
            'iss' => $conf['iss'],
            'iat' => $signTime,
            'exp' => $signTime + $conf['exp'],
        ],
            $conf['secretKey'],
            $conf['algorithms']
        );
        return $token;
    }

    /**
     * jwt 解密
     * @return array
     */
    public function parseToken(string $token): array
    {
        $conf = config('jwt');
        try {
            $decoded = JWT::decode($token, new Key($conf['secretKey'], 'HS256'));
            return json_decode(json_encode($decoded), true);
        } catch (\Throwable $th) {
            Log::error('parseToken: ' . $th->getMessage());
            return [];
        }
    }
}
